package airwallex

import (
	"context"
	"errors"
	"fmt"
	model2 "simplifly-tech/payment/model"
	"simplifly-tech/utility/log"

	"strconv"
	"time"

	"github.com/goccy/go-json"
	"github.com/shopspring/decimal"
)

func (airwallexService *AirwallexService) Refund(ctx context.Context, refundData *model2.RefundData) (string, error) {

	return airwallexService.createRefund(
		refundData.OrderID+"-"+strconv.Itoa(int(refundData.ParentIncomeID)),
		refundData.OrderID+"-"+strconv.Itoa(int(refundData.IncomeID)),
		refundData.ReferenceID,
		refundData.Amount,
	)

}

func (airwallexService *AirwallexService) createRefund(orderId, refundRequestId, uniqueOrderNo string, refundAmount decimal.Decimal) (result string, err error) {
	reqData := AirWallerRefundReq{
		Amount:          refundAmount,
		Reason:          "Refund Money",
		RequestId:       fmt.Sprintf("%d %s", time.Now().Unix(), orderId),
		PaymentIntentId: uniqueOrderNo,
		//PaymentAttemptId: orderId,
	}
	reqData.Metadata.Id = refundRequestId
	payResp, err := airwallexService.getResponse(SendCodeCreateRefund, reqData, "POST")
	if nil != err {
		return "", err
	}

	var respData AirWallerRefundResp
	err = json.Unmarshal(payResp, &respData)
	if err != nil {
		log.Errorf("(airwallexService *AirwallexService) createRefund airwallex反序列化异常： %v", err)
		return "", err
	}
	if respData.Status == "FAILED" {
		log.Errorf("(airwallexService *AirwallexService) createRefund code :%s message :%s", respData.Code, respData.Message)
		return "", errors.New(respData.Message)
	}
	return respData.Id, nil
}
